const jwt = require('jsonwebtoken')
const { User } = require('../models')

const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key'

async function authenticateToken(req, res, next) {
  const authHeader = req.headers['authorization']
  const token = authHeader && authHeader.split(' ')[1]

  if (!token) {
    return res.status(401).json({ error: '未提供访问令牌' })
  }

  try {
    const decoded = jwt.verify(token, JWT_SECRET)
    const user = await User.findByPk(decoded.userId)
    
    if (!user || !user.isActive) {
      return res.status(403).json({ error: '用户不存在或已被禁用' })
    }

    req.user = { userId: user.id, email: user.email }
    next()
  } catch (error) {
    console.error('验证令牌错误:', error)
    res.status(403).json({ error: '无效的访问令牌' })
  }
}

module.exports = { authenticateToken }
